package ca.utoronto.cms.cscc85.project4.teamrf;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.HashMap;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import ca.utoronto.cms.cscc85.project4.teamrf.R;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.content.Intent;
import android.database.*;
import android.database.sqlite.SQLiteDatabase;

/**
 * This is the main page of our application. It sets up the main GUI.
 * 
 */
public class Main extends Activity implements OnClickListener {
	private Button searchButton, addRecipeButton, viewAllButton; // button
																	// objects
	public static SQLiteDatabase db; // database object
	public static Cursor results; // stores database query results
	private final String UPDATE_URL = "http://www.scar.utoronto.ca/~07wongry/recipe.json";
	private JSONObject json = getJSONfromURL(UPDATE_URL);

	/** Called when the activity is first created. */
	@Override
	/**
	 * This method creates the page according to the xml file main.xml
	 */
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);

		// Link all buttons and set onClickListeners
		searchButton = (Button) findViewById(R.id.searchRecipesButton);
		searchButton.setOnClickListener(this);
		addRecipeButton = (Button) findViewById(R.id.addRecipeButton);
		addRecipeButton.setOnClickListener(this);
		viewAllButton = (Button) findViewById(R.id.viewAllButton);
		viewAllButton.setOnClickListener(this);

		Main.db = this.openDatabase(); // Initialise database connection
		handlejson();
	}
	/**
	 * Parses the json file and transform it into sql statements.
	 * 
	 */
	private void handlejson() {
		try {
			// Get the element that holds the recipes ( JSONArray )
			JSONArray r = json.getJSONArray("recipes");
			
			//give new index to entries
			String getIDSQL = "SELECT _id FROM recipes ORDER BY _ID DESC LIMIT 1";
			String updatequery;
			Cursor results = Main.getDatabase().rawQuery(getIDSQL, null);
			results.moveToNext();				
			Integer ids = results.getInt(0) + 1; //make unique ids
			results.close();
			
			// Loop the Array
			for (int i = 0; i < r.length(); i++) {
				JSONObject oner = r.getJSONObject(i);
				//insert json entry into table
				updatequery = "INSERT INTO recipes VALUES(" + Integer.toString(ids) + ", '" + 
		                oner.getString("name") + "','" + oner.getString("ingredients") + "','" + oner.getString("direction") + "'," 
		                + oner.getString("time") + ")";
				
				Main.getDatabase().execSQL(updatequery);
				ids+=1;
			}
		} catch (JSONException e) {
			Log.e("log_tag", "Error parsing data " + e.toString());
		}

	}

	/**
	 * This function makes it easy for other classes easy access to the database
	 * connection
	 * 
	 * @return SQLIte object
	 */
	public static SQLiteDatabase getDatabase() {
		return Main.db;
	}

	/**
	 * helps set up the connection to the database if it exist or needs to be
	 * created.
	 * 
	 * @return
	 */
	private SQLiteDatabase openDatabase() {
		DBHandler importer = new DBHandler(this);

		try {
			importer.createDataBase();
		} catch (IOException e) {
			throw new Error("Unable to create database");
		}

		try {
			importer.openDataBase();
		} catch (SQLException e) {
			throw new Error("Unable to open database");
		}

		return importer.myDataBase;
	}

	/**
	 * This function is called every time a button is clicked
	 */
	public void onClick(View v) {
		// search button is clicked
		if (v == searchButton) {
			Intent searchIntent = new Intent(this, SearchRecipesActivity.class);
			startActivity(searchIntent);

			// view button is clicked
		} else if (v == viewAllButton) {
			// start ViewResultsActivity with all recipes
			String query;
			query = "SELECT * FROM recipes"; // finds all recipes
			results = this.getDatabase().rawQuery(query, null);

			// go to the view all recipe activity page
			Intent viewAllIntent = new Intent(this, ViewResultsActivity.class);
			startActivity(viewAllIntent);

			// add recipe button is clicked
		} else if (v == addRecipeButton) {
			// start AddRecipeActivity
			Intent addIntent = new Intent(this, AddRecipeActivity.class);
			startActivity(addIntent);
		}
	}
	/**
	 * Gets the json file form the url and returns a json object
	 * @param url
	 * @return
	 */
	public static JSONObject getJSONfromURL(String url) {
		// initialize
		InputStream is = null;
		String result = "";
		JSONObject jArray = null;
		// http post
		try {
			HttpClient httpclient = new DefaultHttpClient();
			HttpPost httppost = new HttpPost(url);
			HttpResponse response = httpclient.execute(httppost);
			HttpEntity entity = response.getEntity();
			is = entity.getContent();
		} catch (Exception e) {
			Log.e("log_tag", "Error in http connection " + e.toString());
		}
		// convert response to string
		try {
			BufferedReader reader = new BufferedReader(new InputStreamReader(
					is, "iso-8859-1"), 8);
			StringBuilder sb = new StringBuilder();
			String line = null;
			while ((line = reader.readLine()) != null) {
				sb.append(line + "\n");
			}
			is.close();
			result = sb.toString();
		} catch (Exception e) {
			Log.e("log_tag", "Error converting result " + e.toString());
		}
		// try parse the string to a JSON object
		try {
			jArray = new JSONObject(result);
		} catch (JSONException e) {
			Log.e("log_tag", "Error parsing data " + e.toString());
		}
		return jArray;

	}

}